package com.ejuornal.util;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

public class UploadUtil {
	public static String upload(File file, String fileName) {
		String realPath = ServletActionContext.getServletContext().getRealPath("/attached/images");
        String dbPicSrc = null;//存储路径
        if(file != null){
            File saveDir = new File(realPath);
            //图片重命名
            String ext = fileName.split("\\.")[1];//后缀名
            Calendar cal = Calendar.getInstance();
            String reName = String.valueOf(cal.getTimeInMillis());
            dbPicSrc = "attached/images/"+reName+"."+ext;
            fileName = reName+"."+ext;
            
            if(!saveDir.exists()){
            	saveDir.mkdirs();
            }
            File saveFile = new File(saveDir, fileName);
            try {
            	FileUtils.copyFile(file, saveFile);
            } catch (IOException e) {
            	e.printStackTrace();
            }
        }
		return dbPicSrc;
	}
}
